﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using MusicOnLine.Models;
using System.Collections.Specialized;
using System.Data;

namespace MusicOnLine.Common
{
    public class MOLMembershipProvider:MembershipProvider
    {
        private string applicationName;
        private MembershipPasswordFormat passwordFormat;
        MusicPlayEntities DB = new MusicPlayEntities();
        #region Properties    

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }
        #endregion

        #region Method

        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "DbMembershipProvider";
            }
            applicationName = config["applicationName"];
            passwordFormat = MembershipPasswordFormat.Clear;
            base.Initialize(name, config);
        } 

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public MembershipUser CreateUser(MusicOnLine.Models.Membership member,out MembershipCreateStatus status)
        {
            if (GetUserNameByEmail(member.Email) != "")
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }
            MembershipUser u = GetUser(member.UserName,false);
            if (u == null)
            {
                DB.Memberships.Add(member);
                DB.SaveChanges();
                status = MembershipCreateStatus.Success;
                return GetUserFromMemberModel(member);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }
           
        }


        private  MOLMemberUser GetUserFromMemberModel(MusicOnLine.Models.Membership member)
        {
            MOLMemberUser u = new MOLMemberUser(this.Name, member.UserName, member.UserID, member.Email,
                member.PasswordQuestion == null ? "" : member.PasswordQuestion, member.Commnet == null ? "" : member.Commnet,
                member.IsApproved == null ? false : (bool)member.IsApproved, member.IsLockedOut == null ? false : (bool)member.IsLockedOut,
                member.CreateDate == null ? new DateTime() : (DateTime)member.CreateDate, member.LastLoginDate == null ? new DateTime() : (DateTime)member.LastLoginDate,
                new DateTime(), member.LastPasswordChangedDate == null ? new DateTime() : (DateTime)member.LastPasswordChangedDate,
                member.LastLockoutDate == null ? new DateTime() : (DateTime)member.LastLockoutDate, member.MobilePhone, member.ImgUrl);
            return u;
           
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            try
            {
                var user = DB.Memberships.Single(o => o.UserName == username);
                DB.Memberships.Remove(user);
                if (deleteAllRelatedData)
                {
                    foreach (var item in DB.UsersInRoles.Where(o => o.UserID == user.UserID))
                    {
                        DB.Entry(item).State = EntityState.Deleted;
                    }
                }
                DB.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }              

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection collection = new MembershipUserCollection();
            var list = DB.Memberships.Where(o => o.Email.IndexOf(emailToMatch) >= 0).ToList();
            foreach (var item in list)
            {
                collection.Add(GetUserFromMemberModel(item));
            }
            totalRecords = list.Count();
            return collection;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection collection = new MembershipUserCollection();
            var list = DB.Memberships.Where(o => o.UserName.IndexOf(usernameToMatch) >= 0).ToList();
            foreach (var item in list)
            {
                collection.Add(GetUserFromMemberModel(item));
            }
            totalRecords = list.Count();
            return collection;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection collection = new MembershipUserCollection();
            var list = DB.Memberships.ToList();
            foreach (var item in list)
            {
                collection.Add(GetUserFromMemberModel(item));
            }
            totalRecords = list.Count();
            return collection;
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            var member = DB.Memberships.Where(o => o.UserName == username);
            MOLMemberUser u = null;
            if (member.Count()> 0)
            {
                u = GetUserFromMemberModel(member.First());               
            }
            return u;
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            var member = DB.Memberships.Single(o => o.UserID == (Guid)providerUserKey);
            MOLMemberUser u = null;
            if (member != null)
            {
                u = GetUserFromMemberModel(member);
            }
            return u;
        }

        public override string GetUserNameByEmail(string email)
        {
            var user = DB.Memberships.Where(o => o.Email == email);
            if (user.Count()==0)
            {
                return "";
            }
            else
            {
                return user.First().UserName;
            }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            var u = (MOLMemberUser)user;
            MusicOnLine.Models.Membership member = DB.Memberships.Single(o => o.UserID == (Guid)user.ProviderUserKey);
            member.Commnet = user.Comment;
            member.Email = user.Email;
            
            DB.SaveChanges();            
        }

        public override bool ValidateUser(string username, string password)
        {
            var user = DB.Memberships.Where(o => o.UserName == username && o.Password == password).Count();
            if (user <= 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion
    }
}